import toml from "toml";
import { loadFile } from "../api/base/file";
import {getStore,setStore } from "./storage"
import {replaceObj} from "./temp"
import {getToken,getRefreshToken} from "./token"
//
const KEY = 'THE_WEB_CONFIG'
// 加载 toml 数据
export const loadToml = async (name:string, cs = "utf8") => {
  const file = await loadFile(name);
  return new Promise((resolve, reject) => {
    try {
      const str = file.data;
      const t = toml.parse(str);
      resolve(t);
    } catch (e:any) {
      console.error(
        "Parsing error on line " +
          e.line +
          ", column " +
          e.column +
          ": " +
          e.message
      );
    }
  });
};

// 加载配置文件，并保存配置文件
export const initWebConfig = async () => {
  // 如果打算用接口来替换配置文件,可以重写这里的获取数据的逻辑
  const config = await loadToml("website.toml");
  //
  if (config) {
    setStore(KEY,config)
    // localStorage.setItem("webconfig", JSON.stringify(config));
  }
  return config;
};

//
export const getWebConfig = async (isRefresh = false) => {
  // const s = localStorage.getItem("webconfig");
  const {value:s,time} = getStore(KEY,true)
  const cd = new Date().getTime() - time;
  if (s == undefined || cd > s.cacheTimeout) {
    return await initWebConfig();
  } 
  if(s.isRefresh && isRefresh){
    initWebConfig();
  }
  return s;
};

export const getWebName = () => {
  const d = getStore(KEY) || {name:""};
  return d.name;
}

export const getPrefixName = (name:string,split='-') => {
  if(name == undefined){
    return name;
  }
  const cn = getWebName();
  return `${cn}${split}${name}`
}


export const getWebConfigFromLocal = () => {
  return getStore(KEY)
}


export const getContext = () => {
  const config = getWebConfigFromLocal(); 
  const ctx = {...window,$get:getStore,$c:config}
  if(!config){
    return ctx;
  }
  const token = getToken()
  const refreshToken = getRefreshToken()
  const res = replaceObj(config.context,ctx)
  return {...res,token,refreshToken}
}

export const initI18nLocal = ($i18n:any) => {
  const config = getWebConfigFromLocal()
  const {availableLocales} = $i18n;
  const {i18n} = config;
  if(i18n && availableLocales.includes(i18n)){
    setI18nLanguage($i18n,i18n)
  }
}

const setI18nLanguage = (i18n:any, locale:string) => {
  if (i18n.mode === 'legacy') {
    i18n.locale = locale
  } else {
    i18n.locale.value = locale
  }
  /**
   * NOTE:
   * If you need to specify the language setting for headers, such as the `fetch` API, set it here.
   * The following is an example for axios.
   *
   * axios.defaults.headers.common['Accept-Language'] = locale
   */
  // @ts-ignore
  document.querySelector('html').setAttribute('lang', locale)
}